package com.qiche.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

@Aspect
@Component
public class HttpAspect {

	private final static Logger log=LoggerFactory.getLogger(HttpAspect.class);

	private ThreadLocal<Long> elaspedTime = new ThreadLocal<Long>();
	//@Pointcut("execution(public * com.qiche.controller.wx..*.*(..))")
    public void webLog(){}
	
	//@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) {
		elaspedTime.set(System.currentTimeMillis());
		// 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        StringBuilder requestLog = new StringBuilder();
        requestLog.append(">>>>>>接收请求\n");
        requestLog.append("URL: ").append(attributes.getRequest().getRequestURL()).append("\n");
        requestLog.append("请求方式: ").append(attributes.getRequest().getMethod()).append("\n");
        requestLog.append("执行方法 : ").append(joinPoint.getSignature().getDeclaringTypeName()).append("#").append(joinPoint.getSignature().getName()).append("\n");
        requestLog.append("参数体: ").append(JSONObject.toJSON(joinPoint.getArgs()));
        log.info(requestLog.toString());
	}
	
	//@AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable{
		long s = elaspedTime.get();
        // 处理完请求，返回内容
		log.info("<<<<<<响应内容: {}, 耗时: {}ms", JSONObject.toJSON(ret), (System.currentTimeMillis() - s));
    }
}
